/**
 * Created by apple on 2017/7/6.
 */

var postHelp = module.exports;
var http = require('http');
var querystring = require('querystring');
var Config = require('../config');
var request = require('request');

//cb(err,data)
postHelp.post = function (host, path, port, contentsInfo, isJson, cb) {

    if (!host || !path || !port || !contentsInfo || !isJson) {
        cb('方法参数不为空');
        return;
    }

    var contents = querystring.stringify(contentsInfo);

    var options = {

        hostname: host,
        path: path,
        port: port,
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': contents.length
        }
    }

    var req = http.request(options, function (res) {
        res.setEncoding('utf8');

        var jsonData;
        res.on('data', function (data) {

            if (jsonData) {
                jsonData += data;
            } else {
                jsonData = data;
            }
        });
        res.on('end', function () {

            try {
                if (isJson == true) { //要求返回的是json数据

                    // console.log(jsonData);
                    if (jsonData.indexOf('<html') > 0) {
                        cb('数据格式有误');
                        return;
                    }
                    var res = JSON.parse(jsonData);
                    if (res.status == 200 && res.payload) {
                        cb(null, res.payload);
                    } else {
                        cb(res.err, res.status);
                    }
                } else { //要求返回的是xml数据
                    if (jsonData.indexOf('<html>') > 0) {
                        cb(null, jsonData);
                        return;
                    }
                    cb('数据格式有误');
                }
            } catch (e) {
                cb(e);
                console.log(e);
                return;
            }


        });
    });


    req.on('error', function (err) {
        console.log(err);
        cb(err);
        return;
    });

    req.write(contents);
    req.end;

}

postHelp.baseRequest = function (url, param, callback) {
    url += '?';

    for (var key in param) {
        if (!param[key]) {
            continue;
        }
        url += key + '=' + param[key] + '&';
    }
    url = url_encode(url.substr(0, url.length - 1));

    console.log(url);

    var options = {
        url: url,
        method: 'POST'
    };

    request(options, function (error, response, body) {

        if (error && response && response.statusCode != 200 && !body) {
            callback('1服务器异常，请稍后重试');
            console.log(error);
            return;
        } else {
            if (body == 'success') {
                callback(null, body);
                return;
            }
            if (body && typeof body != 'string') {
                callback(null, body);
                return;
            }
            try {
                body = JSON.parse(body);
                callback(null, body);
            } catch (e) {
                callback('2服务器异常，请稍后重试');
            }
        }
    });
}

postHelp.baseRequestByJson = function (url, param, callback) {
    console.log(url);

    var option = {
        url: url,
        method: "POST",
        json: true,
        headers: {
            "content-type": "application/json",
        },
        body: param
    };

    request(option, function (error, response, body) {
        if (error && response && response.statusCode != 200 && !body) {
            callback('服务器异常，请稍后重试1');
            console.log(error);
            return;
        } else {
            if (body == 'success') {
                callback(null, body);
                return;
            }

            if (body && typeof body != 'string') {
                callback(null, body);
                return;
            }

            try {
                console.log('-----------------------');
                console.log(body);
                body = JSON.parse(body);
                callback(null, body);
            } catch (e) {
                callback('服务器异常，请稍后重试2');
            }
        }
    });
}

postHelp.request = function (host, path, param, callback) {
    var url = host + path;
    var form = '';
    for (var key in param) {
        form += key + '=' + param[key] + '&';
    }
    var options = {
        url: url,
        method: 'POST',
        form: form
    };
    request(options, function (error, response, body) {
        if (error || !response || response.statusCode != 200 || !body) {
            callback('服务器异常，请稍后重试');
            console.log(error);
            return;
        } else {
            try {
                body = JSON.parse(body);
                if (body.status == 200) {
                    callback(null, body.payload);
                    return;
                }
                callback(body.err);
            } catch (e) {
                callback('服务器异常，请稍后重试');
            }
        }
    });
}

function url_encode(url) {
    url = encodeURIComponent(url);
    url = url.replace(/\%3A/g, ":");
    url = url.replace(/\%2F/g, "/");
    url = url.replace(/\%3F/g, "?");
    url = url.replace(/\%3D/g, "=");
    url = url.replace(/\%26/g, "&");

    return url;
}